package com.qf.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.dao.SysMenuMapper;
import com.qf.dto.DataGridResult;
import com.qf.dto.QueryDTO;
import com.qf.pojo.SysMenu;
import com.qf.service.SysMenuService;
import com.qf.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Zhengjz
 * @version 1.0
 * @className SysMenuServiceimpl
 * @date 2021/1/27 14:09
 */
@Service
public class SysMenuServiceimpl implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<String> findMenuByUserId(Long userid) {
        List<String> permsByUserId = sysMenuMapper.findPermsByUserId(userid);
        System.out.println("权限："+permsByUserId);
        Set<String> set = new HashSet<String>();
        for (String s : permsByUserId) {
            if(s!=null&&!s.equals("")){
                String[] split = s.split(",");
                for (String s1 : split) {
                    set.add(s1);
                }
            }
        }
        List<String> perms = new ArrayList<>();
        perms.addAll(set);
        return perms;
    }


    @Override
    public DataGridResult findMenu(QueryDTO queryDTO) {
        PageHelper.offsetPage(queryDTO.getOffset(),queryDTO.getLimit());
        if(queryDTO.getSort()!=null&&!queryDTO.getSort().equals("")){
            queryDTO.setSort("menu_id");
        }
        List<SysMenu> menuByPage = sysMenuMapper.findMenuByPage(queryDTO);
        PageInfo<SysMenu> info = new PageInfo<SysMenu>(menuByPage);
        long total = info.getTotal();

        DataGridResult result = new DataGridResult(total,info.getList());
        return result;
    }

    @Override
    public R findUserMenu(Long userId) {
        //查询用户的一级目录
        List<Map<String, Object>> dirMenuByUserId = sysMenuMapper.findDirMenuByUserId(userId);
        //查询目录对应的子菜单
        for (Map<String, Object> map : dirMenuByUserId) {
            Long menuId = Long.parseLong(map.get("menuId")+"");
            List<Map<String, Object>> subList = sysMenuMapper.findMenuNotButtonByUserId(userId, menuId);
            map.put("list",subList);
        }
        List<String> permsByUserId = findMenuByUserId(userId);
        return R.ok().put("menuList",dirMenuByUserId).put("permissions",permsByUserId);
    }
}
